import 'package:flutter/cupertino.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:get/get.dart';
import 'package:wanandroid_flutter/bean/app_response.dart';
import 'package:wanandroid_flutter/bean/user_info_entity.dart';
import 'package:wanandroid_flutter/controller/home_controller.dart';
import 'package:wanandroid_flutter/controller/mine_controller.dart';
import 'package:wanandroid_flutter/network/api.dart';
import 'package:wanandroid_flutter/network/request_util.dart';
import 'package:wanandroid_flutter/utils/user.dart';

///登录控制器
class LoginController extends GetxController {
  TextEditingController userCtr = TextEditingController();
  TextEditingController passwordCtr = TextEditingController();

  var homeController = Get.find<HomeController>();

  var mineController = Get.find<MineController>();

  ///登录请求
  Future httpLogin() async {
    if (userCtr.text.isEmpty) {
      Fluttertoast.showToast(msg: "请输入用户名");
      return;
    }
    if (passwordCtr.text.isEmpty) {
      Fluttertoast.showToast(msg: "请输入密码");
      return;
    }
    AppResponse<UserInfoEntity> userRes = await HttpGo.instance.post(Api.login,
        data: {"username": userCtr.text, "password": passwordCtr.text});
    if (userRes.isSuccessful) {
      //登录成功
      var userInfo = userRes.data;
      if (userInfo != null) {
        User().loginSuccess(userInfo);
        Get.back();
        homeController.refreshRequest();
        mineController.updateUserInfo(
            userInfo.nickname ?? "登录", userInfo.coinCount ?? 0);
      }
    } else {
      Fluttertoast.showToast(msg: userRes.errorMsg.toString());
    }
  }
}
